package yin.com.dao;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.RowProcessor;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import yin.com.dao.base.BaseDao;
import yin.com.model.User;
import yin.com.utils.JDBCUtil;

import java.sql.SQLException;
import java.util.Map;

public class UserDao extends BaseDao<User> {
    public User finUserByName(String username) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        //开启下划线->驼峰转换所用
        RowProcessor processor = new BasicRowProcessor(new GenerousBeanProcessor());
        User user = null;
        try {
            user = qr.query("select * from user where username = ? limit 1", new BeanHandler<>(User.class,processor), username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    public Map<String, Object> findUserdaoByid(Integer userId) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        Map<String,Object> map=null;
        try {
            String sql = "select u.id,u.username,u.dept_id as deptId,d.`name` as deptName " +
                    "from user u " +
                    "left join dept d on u.dept_id = d.id " +
                    "where u.id = ?";
            map=qr.query(sql, new MapHandler(),userId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    public User findUserByEmail(String email) {
        QueryRunner qr = new QueryRunner(JDBCUtil.getDataSource());
        RowProcessor processor = new BasicRowProcessor(new GenerousBeanProcessor());
        User user=null;
        try {
            user = qr.query("select * from user where email = ? limit 1", new BeanHandler<>(User.class,processor), email);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return user;
    }
}
